import * as PIXI from 'pixi.js';
import { GameConfig } from '../config';

export interface GameOverCallbacks {
    onContinue: () => void;
    onRestart: () => void;
}

export interface LevelCompleteCallbacks {
    onContinue: () => void;
}

export class UI {
    public container: PIXI.Container;
    private config: GameConfig;
    private levelText: PIXI.Text;
    private speedText: PIXI.Text;
    private countdownText: PIXI.Text;
    private gameOverContainer: PIXI.Container;
    private gameOverText: PIXI.Text;
    private levelDisplay: PIXI.Text;
    private app: PIXI.Application;

    constructor(config: GameConfig, app: PIXI.Application) {
        this.app = app;
        this.config = config;
        this.container = new PIXI.Container();
        
        // 创建UI元素
        this.levelText = this.createLevelText();
        this.speedText = this.createSpeedText();
        this.countdownText = this.createCountdownText();
        this.gameOverContainer = this.createGameOverContainer();
        
        // 添加到容器
        this.container.addChild(this.levelText);
        this.container.addChild(this.speedText);
        this.container.addChild(this.countdownText);
        this.container.addChild(this.gameOverContainer);
        
        // 初始隐藏一些元素
        this.countdownText.visible = false;
        this.gameOverContainer.visible = false;
    }

    private createLevelText(): PIXI.Text {
        const style = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 24,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 4,
            dropShadow: true,
            dropShadowColor: '#000000',
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 2,
        });
        
        const text = new PIXI.Text('关卡: 1', style);
        text.x = 20;
        text.y = 20;
        
        return text;
    }

    private createSpeedText(): PIXI.Text {
        const style = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 24,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 4,
            dropShadow: true,
            dropShadowColor: '#000000',
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 2,
        });
        
        const text = new PIXI.Text('车速: 60 km/h', style);
        text.x = this.config.screenWidth - 180;
        text.y = 20;
        
        return text;
    }

    private createCountdownText(): PIXI.Text {
        const style = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 72,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 6,
            dropShadow: true,
            dropShadowColor: '#000000',
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 2,
        });
        
        const text = new PIXI.Text('3', style);
        text.anchor.set(0.5);
        text.x = this.config.screenWidth / 2;
        text.y = this.config.screenHeight / 2;
        
        return text;
    }

    private createGameOverContainer(): PIXI.Container {
        const container = new PIXI.Container();
        
        // 半透明背景
        const bg = new PIXI.Graphics();
        bg.beginFill(0x000000, 0.7);
        bg.drawRect(0, 0, this.config.screenWidth, this.config.screenHeight);
        bg.endFill();
        container.addChild(bg);
        
        // Game Over 文本
        const gameOverStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 48,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 6,
        });
        
        this.gameOverText = new PIXI.Text('游戏结束', gameOverStyle);
        this.gameOverText.anchor.set(0.5);
        this.gameOverText.x = this.config.screenWidth / 2;
        this.gameOverText.y = this.config.screenHeight / 2 - 100;
        container.addChild(this.gameOverText);
        
        // 关卡显示
        const levelStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 32,
            fill: '#ffffff',
        });
        
        this.levelDisplay = new PIXI.Text('', levelStyle);
        this.levelDisplay.anchor.set(0.5);
        this.levelDisplay.x = this.config.screenWidth / 2;
        this.levelDisplay.y = this.config.screenHeight / 2;
        container.addChild(this.levelDisplay);
        
        // 按钮容器（垂直排列）
        const buttonsContainer = new PIXI.Container();
        buttonsContainer.x = this.config.screenWidth / 2;
        buttonsContainer.y = this.config.screenHeight / 2 + 50;
        
        // 继续游戏按钮（上方）
        const continueButton = this.createButton('继续游戏', 0);
        continueButton.y = 0;
        
        // 重新开始按钮（下方）
        const restartButton = this.createButton('重新开始', 0);
        restartButton.y = 80;  // 在继续按钮下方80像素
        
        buttonsContainer.addChild(continueButton);
        buttonsContainer.addChild(restartButton);
        container.addChild(buttonsContainer);
        
        return container;
    }

    private createButton(text: string, xOffset: number): PIXI.Container {
        const button = new PIXI.Container();
        button.x = xOffset;
        
        // 按钮背景
        const bg = new PIXI.Graphics();
        bg.beginFill(0x3498db);
        bg.drawRoundedRect(-100, -25, 200, 50, 10);
        bg.endFill();
        button.addChild(bg);
        
        // 按钮文本
        const style = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 24,
            fill: '#ffffff',
        });
        
        const buttonText = new PIXI.Text(text, style);
        buttonText.anchor.set(0.5);
        button.addChild(buttonText);
        
        // 设置交互
        button.eventMode = 'static';
        button.cursor = 'pointer';
        
        return button;
    }

    public updateLevel(level: number): void {
        this.levelText.text = `关卡: ${level}`;
    }

    public updateSpeed(speedKmh: number): void {
        this.speedText.text = `车速: ${Math.round(speedKmh)} km/h`;
    }

    public showLevelStart(level: number, onComplete: () => void): void {
        this.countdownText.visible = true;
        
        // 先显示关卡数
        const levelStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 48,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 6,
            align: 'center'
        });
        
        this.countdownText.style = levelStyle;
        this.countdownText.text = `Level ${level}`;
        
        // 1.5秒后显示 GO!
        setTimeout(() => {
            const goStyle = new PIXI.TextStyle({
                fontFamily: 'Arial',
                fontSize: 72,
                fontWeight: 'bold',
                fill: '#2ecc71',  // 绿色
                stroke: '#000000',
                strokeThickness: 6,
                align: 'center'
            });
            
            this.countdownText.style = goStyle;
            this.countdownText.text = 'GO!';
            
            // 0.8秒后隐藏并开始游戏
            setTimeout(() => {
                this.countdownText.visible = false;
                onComplete();
            }, 800);
        }, 1500);
    }

    public showGameOver(level: number, callbacks: GameOverCallbacks): void {
        // 更新关卡显示
        this.levelDisplay.text = `Level ${level}`;
        
        // 显示游戏结束界面
        this.gameOverContainer.visible = true;
        
        // 设置按钮事件
        const buttonsContainer = this.gameOverContainer.getChildAt(3) as PIXI.Container;
        const continueButton = buttonsContainer.getChildAt(0);
        const restartButton = buttonsContainer.getChildAt(1);
        
        // 继续按钮
        continueButton.addEventListener('pointertap', () => {
            this.gameOverContainer.visible = false;
            callbacks.onContinue();
        });
        
        // 重新开始按钮
        restartButton.addEventListener('pointertap', () => {
            this.gameOverContainer.visible = false;
            callbacks.onRestart();
        });
    }

    public hideGameOver(): void {
        this.gameOverContainer.visible = false;
        
        // 移除按钮事件监听器
        const buttonsContainer = this.gameOverContainer.getChildAt(3) as PIXI.Container;
        const continueButton = buttonsContainer.getChildAt(0);
        const restartButton = buttonsContainer.getChildAt(1);
        
        if (continueButton) {
            continueButton.removeAllListeners();
        }
        if (restartButton) {
            restartButton.removeAllListeners();
        }
    }

    public showLevelComplete(level: number, callbacks: LevelCompleteCallbacks): void {
        // 创建临时容器
        const container = new PIXI.Container();
        
        // 半透明背景
        const bg = new PIXI.Graphics();
        bg.beginFill(0x000000, 0.7);
        bg.drawRect(0, 0, this.config.screenWidth, this.config.screenHeight);
        bg.endFill();
        container.addChild(bg);
        
        // 创建庆祝效果（星星或粒子）
        const stars = new PIXI.Container();
        for (let i = 0; i < 20; i++) {
            const star = new PIXI.Graphics();
            star.beginFill(0xf1c40f);  // 金色
            
            // 随机大小的五角星
            const size = Math.random() * 10 + 5;
            const x = Math.random() * this.config.screenWidth;
            const y = Math.random() * this.config.screenHeight;
            
            // 绘制五角星
            const points = 5;
            const innerRadius = size / 2;
            const outerRadius = size;
            
            for (let j = 0; j < points * 2; j++) {
                const radius = j % 2 === 0 ? outerRadius : innerRadius;
                const angle = (j * Math.PI) / points;
                const pX = Math.cos(angle) * radius;
                const pY = Math.sin(angle) * radius;
                
                if (j === 0) {
                    star.moveTo(pX, pY);
                } else {
                    star.lineTo(pX, pY);
                }
            }
            
            star.endFill();
            star.x = x;
            star.y = y;
            star.rotation = Math.random() * Math.PI * 2;
            
            // 添加动画
            const animate = () => {
                star.rotation += 0.02;
                star.alpha = 0.5 + Math.sin(Date.now() / 500) * 0.5;
            };
            this.app.ticker.add(animate);
            
            stars.addChild(star);
        }
        container.addChild(stars);
        
        // Congratulations 文本
        const congratsStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 48,
            fontWeight: 'bold',
            fill: ['#f1c40f', '#e67e22'],  // 金色渐变
            stroke: '#000000',
            strokeThickness: 6,
            dropShadow: true,
            dropShadowColor: '#000000',
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 6,
        });
        
        const congratsText = new PIXI.Text('恭喜过关！', congratsStyle);
        congratsText.anchor.set(0.5);
        congratsText.x = this.config.screenWidth / 2;
        congratsText.y = this.config.screenHeight / 2 - 100;
        container.addChild(congratsText);
        
        // Level Complete 文本
        const completeStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 32,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 4,
        });
        
        const completeText = new PIXI.Text(`第 ${level} 关通过！`, completeStyle);
        completeText.anchor.set(0.5);
        completeText.x = this.config.screenWidth / 2;
        completeText.y = this.config.screenHeight / 2;
        container.addChild(completeText);
        
        // 下一关提示
        const nextLevelStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 24,
            fill: '#2ecc71',  // 绿色
            stroke: '#000000',
            strokeThickness: 3,
        });
        
        const nextLevelText = new PIXI.Text('准备进入第 ' + (level + 1) + ' 关', nextLevelStyle);
        nextLevelText.anchor.set(0.5);
        nextLevelText.x = this.config.screenWidth / 2;
        nextLevelText.y = this.config.screenHeight / 2 + 50;
        container.addChild(nextLevelText);
        
        // 添加到主容器
        this.container.addChild(container);
        
        // 2秒后自动进入下一关
        setTimeout(() => {
            if (container.parent) {
                // 移除星星动画
                stars.children.forEach(star => {
                    this.app.ticker.remove(star.animate);
                });
                
                this.container.removeChild(container);
                callbacks.onContinue();
            }
        }, 2000);
    }
}